package i18n;

import i18n.adapter.I18nAcceptLanguageAdapter;
import i18n.enums.HttpRequestHeaderAcceptXEnums;
import i18n.enums.I18nPrefixFieldEnum;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
public class I18nManager implements I18nManagerInterface {

    private final String REQUEST_HEADER_KEY = HttpRequestHeaderAcceptXEnums.ACCEPT_LANGUAGE.getValue();

    @Resource
    private I18nAcceptLanguageAdapter acceptLanguageAdapter;

    @Override
    public I18nPrefixFieldEnum getHttpRequestHeaderLanguage() {
        //获得 HttpServletRequest 对象 并从请求头中获取 key == REQUEST_HEADER_KEY 的前缀值
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        return acceptLanguageAdapter.convert(request.getHeader(REQUEST_HEADER_KEY));
    }

    public void i18n(List<? extends I18nInterface> list) {
        I18nPrefixFieldEnum language = getHttpRequestHeaderLanguage();
        for (I18nInterface i18n : list) {
            i18n(i18n, language);
        }
    }

    public void i18n(Map<Object, ? extends I18nInterface> map) {
        I18nPrefixFieldEnum language = getHttpRequestHeaderLanguage();
        for (I18nInterface i18n : map.values()) {
            i18n(i18n, language);
        }
    }

    public void i18n(I18nInterface obj) {
        I18nPrefixFieldEnum language = getHttpRequestHeaderLanguage();
        i18n(obj, language);
    }

    private void i18n(I18nInterface obj, I18nPrefixFieldEnum language) {
        if (obj == null || language == null) return;
        switch (language) {
            case ENGLISH:
                obj.english();
                break;
            case DEFAULT:
            case CHINESE:

                break;
        }
    }

}
